package com.scm.www.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.scm.www.pojo.testUser;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.*;



//@Resource(name = "HibernateSession")
//private Session session;
//@Resource(name = "HibernateTransaction")
//private Transaction transaction;


@Configuration
@EnableTransactionManagement
public class HibernateConfigEntityManager {

    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/DBServer?useSSL=false&serverTimezone=UTC");
        druidDataSource.setUsername("admin");
        druidDataSource.setPassword("admin123456");
        druidDataSource.setMaxWait(60000);
        druidDataSource.setTestWhileIdle(false);
        return druidDataSource;
    }
    @Bean
    public SessionFactory hibernateSessionFactory(){

        Map<String,Object> settings = new HashMap<>();
        settings.put("hibernate.connection.datasource",dataSource());
        settings.put("hibernate.format_sql","true");
        settings.put("hibernate.show_sql","true");
        settings.put("hibernate.hbm2ddl.auto","update");
        settings.put("hibernate.dialect","org.hibernate.dialect.MySQL8Dialect");
        settings.put("hibernate.current_session_context_class","thread");
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build();
        List<Class> classList = new ArrayList<>();
        classList.add(testUser.class);
        MetadataSources  sources = null;
        for (Class cs:classList) {
            sources = new MetadataSources(serviceRegistry).addAnnotatedClass(cs);
        }
        SessionFactory sessionFactory =sources.buildMetadata(serviceRegistry).buildSessionFactory();
        return sessionFactory;
    }
    @Bean
    public Session HibernateSession(){
        Session session = hibernateSessionFactory().getCurrentSession();
        return session;
    }
    /**
     * 支持事务回滚
     * */
    @Bean
    public Transaction HibernateTransaction(){
        Transaction transaction = HibernateSession().beginTransaction();
        return transaction;
    }
}
